import isFunction from 'lodash/isFunction';
import isString from 'lodash/isString';
import isArray from 'lodash/isArray';
import isPlainObject from 'lodash/isPlainObject';
import fetchJsonp from 'fetch-jsonp';
import localStorage from 'shared/utils/localStorage';
import { getSsoApi, logoutApi } from 'shared/api';
import Request from './Request';

const exp = /\{\{([\s\S]+?)\}\}/g;
const hasTemplate = s => s.match(exp);
const findTemplate = (s) => {
  const m = exp.exec(s);
  return m ? m[1] : '';
};

const doTemplate = (url, param) => {
  if (isString(url) && isPlainObject(param)) {
    let key = findTemplate(url);
    while (key) {
      let value = param[key] || '';
      if (isArray(value)) {
        value = value.join(',');
      }
      url = url.replace(`{{${key}}}`, value);
      key = findTemplate(url);
    }
  }

  return url;
};

const createAPI = (method, url, isConnectSso = true, isJSON) => (params, content) => {
  let templateHandler;
  if (hasTemplate(url)) {
    templateHandler = doTemplate;
  }

  let restUrl = `/${url}`;
  // let restUrl = `${process.env.NODE_ENV === 'development' ? 'api' : ''}/${url}`;
  if (isFunction(templateHandler)) {
    restUrl = templateHandler(url, params);
  } else {
    content = params;
  }

  const token = localStorage.get('token');
  const uid = localStorage.get('uid');
  isConnectSso = false;

  if (isConnectSso && token) {
    const sessId = localStorage.get('sessId');
    fetchJsonp(getSsoApi(sessId))
      .then(function (response) {
        return response.json()
      })
      .then(function (res) {
        if (parseInt(res.code, 10) === 40001) {
          logoutApi({
            sess_id: sessId,
            uid,
            token
          })
        }
      })
  }

  return Request.instance[method](restUrl, content, isJSON);
};


export default createAPI;
